<template>
  <div class="user-management">
    <div class="management-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名、手机号、真实姓名"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 用户统计卡片 -->
    <div class="stats-row">
      <div class="stat-item">
        <div class="stat-number">{{ userStats.total }}</div>
        <div class="stat-label">总用户数</div>
      </div>
      <div class="stat-item pending">
        <div class="stat-number">{{ userStats.pending }}</div>
        <div class="stat-label">待审核</div>
      </div>
      <div class="stat-item approved">
        <div class="stat-number">{{ userStats.approved }}</div>
        <div class="stat-label">已通过</div>
      </div>
      <div class="stat-item rejected">
        <div class="stat-number">{{ userStats.rejected }}</div>
        <div class="stat-label">已拒绝</div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-table-container">
      <el-table
        :data="filteredUsers"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        
        <el-table-column prop="username" label="用户名" min-width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.avatar" />
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="realName" label="真实姓名" min-width="100" />
        
        <el-table-column prop="phone" label="手机号" min-width="120" />
        
        <el-table-column prop="idCard" label="身份证号" min-width="150">
          <template #default="{ row }">
            <span v-if="row.idCard">{{ maskIdCard(row.idCard) }}</span>
            <span v-else class="no-data">未填写</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="houseAddress" label="房屋地址" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.houseAddress">{{ row.houseAddress }}</span>
            <span v-else class="no-data">未填写</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="houseArea" label="房屋面积" min-width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.houseArea">{{ row.houseArea }}㎡</span>
            <span v-else class="no-data">未填写</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="注册时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="row.status === 0"
                type="success"
                size="small"
                @click="handleApprove(row)"
                :loading="row.loading"
              >
                通过
              </el-button>
              <el-button
                v-if="row.status === 0"
                type="danger"
                size="small"
                @click="handleReject(row)"
                :loading="row.loading"
              >
                拒绝
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetails(row)"
              >
                详情
              </el-button>
              <el-dropdown @command="(command) => handleMoreActions(command, row)">
                <el-button type="info" size="small">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="reset-password">重置密码</el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除用户</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="showDetailsDialog"
      title="用户详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedUser" class="user-details">
        <div class="detail-header">
          <el-avatar :size="80" :src="selectedUser.avatar" />
          <div class="user-basic-info">
            <h3>{{ selectedUser.username }}</h3>
            <p>{{ selectedUser.realName || '未填写真实姓名' }}</p>
            <el-tag :type="getStatusType(selectedUser.status)">
              {{ getStatusText(selectedUser.status) }}
            </el-tag>
          </div>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">{{ selectedUser.username }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ selectedUser.realName || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ selectedUser.phone || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ selectedUser.idCard || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="房屋面积">{{ selectedUser.houseArea ? selectedUser.houseArea + '㎡' : '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="房屋类型">{{ selectedUser.houseType || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="房屋地址" :span="2">{{ selectedUser.houseAddress || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ formatDate(selectedUser.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="最后登录">{{ formatDate(selectedUser.lastLoginTime) || '从未登录' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑用户"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="editForm.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房屋面积" prop="houseArea">
              <el-input-number
                v-model="editForm.houseArea"
                placeholder="请输入房屋面积"
                style="width: 100%"
                :precision="2"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="房屋类型" prop="houseType">
              <el-select v-model="editForm.houseType" placeholder="请选择房屋类型" style="width: 100%">
                <el-option label="住宅" value="住宅" />
                <el-option label="商铺" value="商铺" />
                <el-option label="办公" value="办公" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="待审核" :value="0" />
                <el-option label="已通过" :value="1" />
                <el-option label="已拒绝" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="房屋地址" prop="houseAddress">
          <el-input
            v-model="editForm.houseAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入房屋地址"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit" :loading="editLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { 
  getUserList, 
  getUserStats, 
  approveUser, 
  rejectUser, 
  updateUser, 
  resetUserPassword, 
  deleteUser 
} from '@/api/auth'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 对话框控制
const showDetailsDialog = ref(false)
const showEditDialog = ref(false)
const selectedUser = ref(null)
const editLoading = ref(false)

// 表单引用
const editFormRef = ref()

// 用户统计
const userStats = reactive({
  total: 0,
  pending: 0,
  approved: 0,
  rejected: 0
})

// 用户列表数据
const users = ref([])

// 编辑表单
const editForm = reactive({
  id: null,
  realName: '',
  phone: '',
  idCard: '',
  houseAddress: '',
  houseArea: null,
  houseType: '',
  status: 0
})

// 编辑表单验证规则
const editRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  houseArea: [
    { type: 'number', min: 0, message: '房屋面积不能小于0', trigger: 'blur' }
  ]
}

// 计算属性 - 过滤后的用户列表
const filteredUsers = computed(() => {
  if (!searchKeyword.value) {
    return users.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(keyword) ||
    (user.realName && user.realName.toLowerCase().includes(keyword)) ||
    (user.phone && user.phone.includes(keyword))
  )
})

// 方法定义
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

const refreshData = () => {
  loadUsers()
  loadStats()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUsers()
}

// 状态相关方法
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning', // 待审核
    1: 'success', // 已通过
    2: 'danger'   // 已拒绝
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 身份证号脱敏
const maskIdCard = (idCard) => {
  if (!idCard || idCard.length < 8) return idCard
  return idCard.substring(0, 6) + '********' + idCard.substring(idCard.length - 4)
}

// 用户操作方法
const handleApprove = async (user) => {
  try {
    await ElMessageBox.confirm('确定要通过该用户的申请吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    user.loading = true
    await approveUser(user.id)
    
    user.status = 1
    ElMessage.success('用户审核通过')
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  } finally {
    user.loading = false
  }
}

const handleReject = async (user) => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入拒绝原因', '拒绝申请', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\S+/,
      inputErrorMessage: '请输入拒绝原因'
    })
    
    user.loading = true
    await rejectUser(user.id, reason)
    
    user.status = 2
    ElMessage.success('用户申请已拒绝')
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  } finally {
    user.loading = false
  }
}

const handleViewDetails = (user) => {
  selectedUser.value = user
  showDetailsDialog.value = true
}

const handleMoreActions = (command, user) => {
  switch (command) {
    case 'edit':
      handleEdit(user)
      break
    case 'reset-password':
      handleResetPassword(user)
      break
    case 'delete':
      handleDelete(user)
      break
  }
}

const handleEdit = (user) => {
  Object.assign(editForm, {
    id: user.id,
    realName: user.realName || '',
    phone: user.phone || '',
    idCard: user.idCard || '',
    houseAddress: user.houseAddress || '',
    houseArea: user.houseArea || null,
    houseType: user.houseType || '',
    status: user.status
  })
  showEditDialog.value = true
}

const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        await updateUser(editForm.id, editForm)
        
        // 更新本地数据
        const userIndex = users.value.findIndex(u => u.id === editForm.id)
        if (userIndex !== -1) {
          Object.assign(users.value[userIndex], editForm)
        }
        
        ElMessage.success('用户信息更新成功')
        showEditDialog.value = false
      } catch (error) {
        ElMessage.error('更新失败：' + (error.message || '未知错误'))
      } finally {
        editLoading.value = false
      }
    }
  })
}

const handleResetPassword = async (user) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？重置后密码将变为"123456"', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await resetUserPassword(user.id)
    
    ElMessage.success('密码重置成功，新密码为：123456')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  }
}

const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？此操作不可恢复', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    await deleteUser(user.id)
    
    // 从本地数据中移除
    const userIndex = users.value.findIndex(u => u.id === user.id)
    if (userIndex !== -1) {
      users.value.splice(userIndex, 1)
    }
    
    ElMessage.success('用户删除成功')
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  }
}

// 数据加载方法
const loadUsers = async () => {
  loading.value = true
  try {
    const response = await getUserList({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    })
    
    if (response.data) {
      users.value = response.data.records || response.data.content || response.data
      total.value = response.data.total || response.data.totalElements || 0
    } else {
      // 如果API还没有实现，使用模拟数据
      const mockUsers = generateMockUsers()
      users.value = mockUsers
      total.value = 150
    }
    
  } catch (error) {
    // 如果API调用失败，使用模拟数据
    console.warn('API调用失败，使用模拟数据:', error)
    const mockUsers = generateMockUsers()
    users.value = mockUsers
    total.value = 150
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await getUserStats()
    
    if (response.data) {
      Object.assign(userStats, response.data)
    } else {
      // 如果API还没有实现，使用模拟数据
      userStats.total = 150
      userStats.pending = 12
      userStats.approved = 128
      userStats.rejected = 10
    }
    
  } catch (error) {
    // 如果API调用失败，使用模拟数据
    console.warn('统计数据API调用失败，使用模拟数据:', error)
    userStats.total = 150
    userStats.pending = 12
    userStats.approved = 128
    userStats.rejected = 10
  }
}

// 生成模拟数据
const generateMockUsers = () => {
  const statuses = [0, 1, 2]
  const houseTypes = ['住宅', '商铺', '办公', '其他']
  const areas = ['北京市朝阳区', '上海市浦东新区', '广州市天河区', '深圳市南山区']
  
  return Array.from({ length: pageSize.value }, (_, index) => ({
    id: (currentPage.value - 1) * pageSize.value + index + 1,
    username: `user${(currentPage.value - 1) * pageSize.value + index + 1}`,
    realName: `用户${(currentPage.value - 1) * pageSize.value + index + 1}`,
    phone: `138${String((currentPage.value - 1) * pageSize.value + index + 1).padStart(8, '0')}`,
    idCard: `11010119900101${String((currentPage.value - 1) * pageSize.value + index + 1).padStart(4, '0')}`,
    houseAddress: `${areas[index % areas.length]}某某小区${index + 1}号楼${index + 1}室`,
    houseArea: 80 + Math.random() * 120,
    houseType: houseTypes[index % houseTypes.length],
    status: statuses[index % statuses.length],
    createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
    lastLoginTime: Math.random() > 0.3 ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString() : null,
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    loading: false
  }))
}

// 组件挂载时加载数据
onMounted(() => {
  loadUsers()
  loadStats()
})
</script>

<style scoped>
.user-management {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.management-header h2 {
  margin: 0;
  color: white;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.stats-row {
  display: flex;
  gap: 24px;
  padding: 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
}

.stat-item.pending {
  border-left: 4px solid #e6a23c;
}

.stat-item.approved {
  border-left: 4px solid #67c23a;
}

.stat-item.rejected {
  border-left: 4px solid #f56c6c;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.user-table-container {
  padding: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 500;
  color: #303133;
}

.no-data {
  color: #c0c4cc;
  font-style: italic;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 用户详情对话框样式 */
.user-details {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.user-basic-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
}

.user-basic-info p {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .management-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: space-between;
  }
  
  .stats-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
